package com.shuqi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.EditTextLengthFilter;
import com.shuqi.activity.viewport.EmailAutoCompleteTextView;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.CheckInputUtils;
import com.shuqi.controller.AccountBindController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.AccountBindModel;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.AccountBindParser.AccountBindParserInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

public class AccountMailBindActivity extends ActivityBase implements IEventListener,
        OnFocusChangeListener, OnClickListener {

    private View mPasswordView;

    private EmailAutoCompleteTextView mEmailText;

    private EditText mPasswordText;

    private TextView mBind;

    private TextView mPasswordPoint;

    private TextView mMailPoint;

    private ImageView mSeePasswordView;

    private AccountBindController mAccountBindController;

    private boolean mIsPasswordVisible = false;

    private ToastDialog mLoadingDialog;

    private String mCurrentMail;

    private String mCurrentPwd;
    
    private CommonTitle mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_account_mailbind);
        mAccountBindController =
                (AccountBindController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_ACCOUNT_BINDPHONE, this);
        mAccountBindController.addEventListener(this);
        initView();
    }

    private void initView() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mEmailText = (EmailAutoCompleteTextView) findViewById(R.id.edit_email);
        mSeePasswordView = (ImageView) findViewById(R.id.img_lock_see);
        mPasswordText = (EditText) findViewById(R.id.edit_password);
        mBind = (TextView) findViewById(R.id.bind_next);
        mPasswordView = findViewById(R.id.layout_bindmail_password);
        mPasswordPoint = (TextView) findViewById(R.id.pwd_point);
        mMailPoint = (TextView) findViewById(R.id.mail_point);
        if (isNeedPwd()) {
            mPasswordView.setVisibility(View.VISIBLE);
            mPasswordPoint.setVisibility(View.VISIBLE);
        } else {
            mPasswordView.setVisibility(View.GONE);
            mPasswordPoint.setVisibility(View.GONE);
        }
        mBind.setOnClickListener(this);
        mSeePasswordView.setOnClickListener(this);
        mEmailText.setOnFocusChangeListener(this);
        mPasswordText.setOnFocusChangeListener(this);
        mEmailText.setSelected(true);
        mPasswordView.setSelected(false);
        InputFilter[] filters = {new EditTextLengthFilter(16)};
        mPasswordText.setFilters(filters);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.title_left){
            ActivityManager.getInstance().finishActivity(this);
        }
        if (view == mSeePasswordView) {
            clickVisibleImg();
        }else if (view == mBind) {
            nextStepBind();
        }
    }

    private void nextStepBind() {
        String emailStr = mEmailText.getText().toString();
        String password = null;
        boolean isEmail = CheckInputUtils.checkEmail(emailStr, mMailPoint);
        if (!isEmail) {
            return;
        }
        if (isNeedPwd()) {
            password = mPasswordText.getText().toString();
            boolean isPwd = CheckInputUtils.checkLoginSettingPassword(password, mPasswordPoint);
            if (!isPwd) {
                return;
            }
        }

        showLoadingDialog(true, false, "正在绑定");
        mCurrentMail = emailStr;
        mCurrentPwd = password;
        mAccountBindController.bind(emailStr, password, AccountBindModel.TYPE_BIND_EMAIL, null,null);

        StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_EMIAL_PAGE_COMPLETE_CLICK);

    }

    private void clickVisibleImg() {
        mIsPasswordVisible = !mIsPasswordVisible;
        int rId = mIsPasswordVisible ? R.drawable.password_visible : R.drawable.password_invisible;
        mSeePasswordView.setImageResource(rId);
        if (mIsPasswordVisible) {
            mPasswordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mPasswordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        String msg = mPasswordText.getText().toString();
        if (!TextUtils.isEmpty(msg)) {
            mPasswordText.setSelection(msg.length());
        }
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onEvent(int event, Object data) {
        if (isFinishing()) {
            return;
        }
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                onNetCallback(data);
                break;
            default:
                hideLoadingDialog();
                showMsg("网络连接超时");
                break;
        }
    }

    private void onNetCallback(final Object data) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                AccountBindParserInfo info = (AccountBindParserInfo) data;
                if (info != null) {
                    String msg = info.message;
                    if (info.resultCode == 200) {
                        updateUserInfoToDB(info);
                        AccountActivity.callRefreshAccountOnResume();
                        gotoAccountBindActivity();
                    }
                    hideLoadingDialog();
                    if (!TextUtils.isEmpty(msg)) {
                        showMsg(msg);
                    }
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    /** 回到绑定界面 */
    private void gotoAccountBindActivity() {
        Intent intent = new Intent(this, AccountBindActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ActivityManager.getInstance().startNextActivity(intent, this);
    }

    /**
     * @param info 存入最新的用户信息
     */
    private void updateUserInfoToDB(AccountBindParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext(),true);
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(mCurrentMail)) {
            user.setEmail(mCurrentMail);
        }
        if (!TextUtils.isEmpty(mCurrentPwd)) {
            user.setPassword(mCurrentPwd);
        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        AccountDao.getInstance().saveUserInfo(user);
    }

    /**
     * 是否显示密码框:非会员用户需要显示
     */
    private boolean isNeedPwd() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext(),true);
        return  !MyAccountManager.isVipUser(user);
    }

    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
        }
        if (isLoading) {
            mLoadingDialog.setDissmisOnClickOutSide(false);
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view.getId() == R.id.edit_password) {
            mPasswordView.setSelected(hasFocus);
        } else if (view.getId() == R.id.edit_email) {
            mEmailText.setSelected(hasFocus);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAccountBindController.onDestroy();
    }

    public static void show(Activity context) {
        Intent intent = new Intent(context, AccountMailBindActivity.class);
        ActivityManager.getInstance().startNextActivity(intent, context);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
